package com.shop.cereshop.app.controller.wallet;

import com.shop.cereshop.app.tencent.im.model.redpacket.SendRedPacketParam;
import com.shop.cereshop.app.param.wallet.ConsumeVO;
import com.shop.cereshop.app.tencent.im.model.transfer.SendTransferOrderParam;
import com.shop.cereshop.app.tencent.im.service.RedPacketService;
import com.shop.cereshop.app.service.wallet.BuyerWalletService;
import com.shop.cereshop.app.tencent.im.service.TransferOrderService;
import com.shop.cereshop.commons.domain.buyer.CereBuyerUser;
import com.shop.cereshop.commons.enums.TransactionTypeEnum;
import com.shop.cereshop.commons.result.Result;
import com.shop.cereshop.commons.constant.CoReturnFormat;
import com.shop.cereshop.commons.utils.EmptyUtils;
import cn.hutool.core.bean.BeanUtil;

import java.util.Objects;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

@Slf4j
@RestController
@RequestMapping("/wallet/consume")
@Api(tags = "钱包消费接口")
public class WalletConsumeController {

    @Autowired
    private BuyerWalletService buyerWalletService;

    @Resource
    private RedPacketService redPacketService;

    @Resource
    private TransferOrderService transferOrderService;

    @ApiOperation("钱包消费")
    @PostMapping("/consume")
    public Result<String> consume(@RequestBody ConsumeVO consumeVO, HttpServletRequest request) {
        try {
            //获取当前登录账户
            CereBuyerUser user = (CereBuyerUser) request.getAttribute("user");
            if (BeanUtil.isEmpty(user)) {
                return new Result(CoReturnFormat.USER_NOT_LOGIN);
            }
            // 手动验证参数
            /*if (consumeVO.getAmount() == null || consumeVO.getAmount().compareTo(BigDecimal.ZERO) <= 0) {
                Result<String> result = new Result<>(CoReturnFormat.PARAM_INVALID);
                result.setMessage("消费金额必须大于0");
                return result;
            }*/
            if (EmptyUtils.isEmpty(consumeVO.getConsumeType())) {
                Result<String> result = new Result<>(CoReturnFormat.PARAM_INVALID);
                result.setMessage("消费类型不能为空");
                return result;
            }
            // 验证支付密码格式（如果提供）
            if (!consumeVO.isPayPasswordValidFormat()) {
                Result<String> result = new Result<>(CoReturnFormat.PARAM_INVALID);
                result.setMessage("支付密码格式错误或解密失败");
                return result;
            }

            // 获取客户端IP地址
            String ipAddress = getClientIpAddress(request);

            // 获取解密后的支付密码
            String decryptedPayPassword = consumeVO.decryptPayPassword();

            boolean success = buyerWalletService.consume(
                    user.getBuyerUserId(), consumeVO.getAmount(), consumeVO.getConsumeType(),
                    consumeVO.getDescription(), consumeVO.getOrderNo(), decryptedPayPassword, ipAddress
            );

            if (success) {
                if (Objects.equals(TransactionTypeEnum.RED_PACKET_PAY.getCode(), consumeVO.getConsumeType())) {
                    SendRedPacketParam param = new SendRedPacketParam();
                    param.setIpAddress(ipAddress);
                    param.setOrderId(consumeVO.getOrderNo());
                    param.setPayMethod(3);
                    redPacketService.send(param);
                } else if (Objects.equals(TransactionTypeEnum.TRANSFER_ORDER_PAY.getCode(), consumeVO.getConsumeType())) {
                    SendTransferOrderParam param = new SendTransferOrderParam();
                    param.setIpAddress(ipAddress);
                    param.setOrderId(consumeVO.getOrderNo());
                    param.setPayMethod(3);
                    transferOrderService.send(param);
                }

                return new Result(CoReturnFormat.SUCCESS);
            } else {
                return new Result(CoReturnFormat.WALLET_CONSUME_FAIL);
            }
        } catch (Exception e) {
            log.error("钱包消费失败", e);
            return new Result(CoReturnFormat.WALLET_CONSUME_FAIL);
        }
    }

    /**
     * 获取客户端IP地址
     *
     * @param request HTTP请求
     * @return IP地址
     */
    private String getClientIpAddress(HttpServletRequest request) {
        String xForwardedFor = request.getHeader("X-Forwarded-For");
        if (xForwardedFor != null && !xForwardedFor.isEmpty() && !"unknown".equalsIgnoreCase(xForwardedFor)) {
            return xForwardedFor.split(",")[0];
        }

        String xRealIp = request.getHeader("X-Real-IP");
        if (xRealIp != null && !xRealIp.isEmpty() && !"unknown".equalsIgnoreCase(xRealIp)) {
            return xRealIp;
        }

        return request.getRemoteAddr();
    }
}
